# 生成器 yield
# 每次使用yield生成一个值后，函数都将冻结，即在此停止执行，等待被重新唤醒。被重新唤醒后，函数将从停止的地方开始继续执行

nestd = [[1, 2], [3, 4], [5, 6]]


# 简单的生成器
def flatten(nes):
    for sublist in nes:
        for ele in sublist:
            yield ele


#  利用循环使用生成器
for n in flatten(nestd):
    print(n)

# 利用list使用生成器
lst = list(flatten(nestd))
print(lst)


## 递归式生成器
def flat_all(nest):
    try:
        for sublist in nest:
            for ele in flat_all(sublist):
                yield ele
    except TypeError:
        yield nest


# [1, 2, 3, 4, 5, 6, 7, 8]
lst = list(flat_all([[[1], 2], 3, 4, [5, [6, 7]], 8]))

print(lst)


def flatten_all(nested):
    try:
        # 使用错误来终止迭代字符串类型对象
        try:
            nested + ''
        except TypeError:
            pass
        else:
            raise TypeError
        for sublist in nested:
            for element in flatten_all(sublist):
                yield element
    except TypeError:
        yield nested


lst = list(flatten_all(['foo', ['bar', ['zzz']]]))
print(lst)  # ['foo', 'bar', 'zzz']


#

# 通用生成器
def simple_generator():
    yield 1


print(simple_generator())

#
